package com.tran.app.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tran.app.MyApp
import com.tran.app.dao.AppDatabase
import com.tran.app.data.Course
import com.tran.app.data.CourseSelectionCancellation
import com.tran.app.data.UserInfo
import com.tran.app.utils.show
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DropCourseScreenVM:ViewModel() {

    fun unbindCourse(it: Course) {
        viewModelScope.launch {
            var issuccess=true
            withContext(Dispatchers.IO){
                val id = AppDatabase.getInstance(MyApp.instance).userInfoDao().getUserByName(MyApp.user)!!.id
                val selectid = AppDatabase.getInstance(MyApp.instance).CourseSelectionDao()
                    .getCourseSelectionByStudentCourseId(id,it.id).id
                val couseleCance = CourseSelectionCancellation(0,it.techaccount,id,it.id,selectid.toLong())
                try {
                    AppDatabase.getInstance(MyApp.instance).courseSelectionCancellationDao().insert(couseleCance)
                }catch (e:Exception){
                   issuccess = false
                }
            }
            if(issuccess){
                show("申请成功")
            }else{
                show("申请失败,已经在申请中")
            }
        }
    }

    private val _uidata = MutableStateFlow<List<Course>>(emptyList())
    val uidata: StateFlow<List<Course>> = _uidata.asStateFlow()

    init {
        viewModelScope.launch {
            withContext(Dispatchers.IO){
                val id = AppDatabase.getInstance(MyApp.instance).userInfoDao().getUserByName(MyApp.user)!!.id
                val list =  AppDatabase.getInstance(MyApp.instance).CourseSelectionDao().
                getCourseSelectionsByStudentId(id)
                val courselist = list.map {
                    AppDatabase.getInstance(MyApp.instance).courseDao().getCoursesById(it.id)
                }
                _uidata.update {
                    courselist
                }
            }
        }
    }

}